<template>
  <div class="ql-editor-wrapper" style="background-color: #fff">
    <div class="ql-editor-header">
      <a-icon type="left" @click="goback" />
      <div class="ql-editor-header-title">设置印章位置</div>
    </div>
    <div class="ql-editor-content ql-editor-content2">
      <div class="editor-main editor-main2">
        <div class="sealnew-name" :style="{ width: `${a4_width}px` }">
          <div class="left" style="flex: 1">{{ name }}.pdf</div>
          <div style="width: 160px; flex-shrink: 0; text-align: right">
            <a-button style="width: 32px; padding: 0; margin-right: 10px" @click="pageUp">
              <a-icon type="left" />
            </a-button>
            {{ currentPage }}/{{ pageCount }}
            <a-button style="width: 32px; padding: 0; margin-left: 10px" @click="pageDown">
              <a-icon type="right" />
            </a-button>
          </div>
        </div>
        <div
          :style="{
            width: `${a4_width}px`,
            position: 'relative',
            margin: '0 auto',
            boxShadow: '0px 2px 16px 0px rgba(0, 0, 0, 0.1)'
          }"
        >
          <pdf
            v-if="src"
            ref="pdf"
            :src="src"
            :page="currentPage"
            @num-pages="pageCount = $event"
            @page-loaded="currentPage = $event"
            @error="pdfError"
          />
          <template v-for="item in dropList">
            <vue-draggable-resizable
              v-if="item.page === currentPage"
              :ref="`${item.type}${item.id}`"
              :key="item.id"
              :parent="true"
              :resizable="false"
              :w="seal_size"
              :h="item.type === 'seal' ? seal_size : item.type === 'sign' ? 50 : 100"
              :x="item.x"
              :y="item.y"
              class-name="editor-main-drag"
              @dragstop="onDrag(arguments, item.id)"
            >
              <div class="editor-main-drag-close">
                <a-popconfirm title="确认要删除合同内的这个印章吗？" ok-text="确认" cancel-text="取消" @confirm="remove(item.id)">
                  <a-icon type="close-circle" />
                </a-popconfirm>
              </div>
              <div v-if="item.type === 'seal'">
                <img src="@/assets/img/seal-circle.png" alt="" />
                <!-- <div class="editor-main-drag-sign">企业签署日期</div> -->
              </div>
              <div v-if="item.type === 'sign'">
                <div class="editor-main-drag-sign">电子签名</div>
                <!-- <div class="editor-main-drag-sign">个人签署日期</div> -->
              </div>
              <div v-if="item.type === 'holder'">
                <div class="editor-main-drag-sign lp">法人章</div>
              </div>
              <!-- <img v-if="item.type === 'seal'" src="@/assets/img/seal-circle.png" alt="">
              <div v-if="item.type === 'seal_date'" class="editor-main-drag-sign">企业签署日期</div>
              <div v-if="item.type === 'sign'" class="editor-main-drag-sign">电子签名</div>
              <div v-if="item.type === 'sign_date'" class="editor-main-drag-sign">个人签署日期</div> -->
            </vue-draggable-resizable>
          </template>
        </div>
      </div>
      <div class="editor-config editor-config2">
        <!-- <div class="editor-config-page">
          <div class="editor-config-page-btn" @click="pageUp">
            <a-icon type="up" />
          </div>
          <div class="editor-config-page-btn" @click="pageDown">
            <a-icon type="down" />
          </div>
        </div> -->
        <div class="editor-config-block" style="border: 0">
          <div class="editor-config-block-content" style="margin-top: 40px">
            <div class="fs14 fw400" style="color: #252525">将印章拖拽至签署位置</div>
            <div v-for="item in dragList" :key="item">
              <div v-if="item === 'seal'" class="editor-tit">
                已添加 <span>{{ seal.length }}</span> 处电子印章
              </div>
              <div v-if="item === 'sign'" class="editor-tit">
                已添加 <span>{{ sign.length }}</span> 处手写签名
              </div>
              <div v-if="item === 'holder'" class="editor-tit">
                已添加 <span>{{ holder.length }}</span> 处手法人章
              </div>
              <div class="editor-config-block-content-drag" style="margin-top: 12px" @click="add(item)">
                <img v-if="item === 'seal'" src="@/assets/img/seal-circle.png" alt="" />
                <div v-if="item === 'seal_date'" class="editor-config-block-content-sign">企业签署日期</div>
                <div v-if="item === 'sign'" class="editor-config-block-content-sign">手写签名</div>
                <div v-if="item === 'sign_date'" class="editor-config-block-content-sign">个人签署日期</div>
                <div v-if="item === 'holder'" class="editor-config-block-content-sign">法人章</div>
              </div>
              <div v-if="item === 'seal'" class="editor-tags">
                <div v-for="(item, index) in sealJson" :key="index" class="editor-tags-item" @click="jump(index)">
                  第{{ index }}页({{ item }})
                </div>
              </div>
              <div v-if="item === 'sign'" class="editor-tags">
                <div v-for="(item, index) in signJson" :key="index" class="editor-tags-item" @click="jump(index)">
                  第{{ index }}页({{ item }})
                </div>
              </div>
              <div v-if="item === 'holder'" class="editor-tags">
                <div v-for="(item, index) in holderJson" :key="index" class="editor-tags-item" @click="jump(index)">
                  第{{ index }}页({{ item }})
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="ql-editor-footer ql-editor-footer2">
      <a-button type="primary" @click="save">保存</a-button>
    </div>
  </div>
</template>
<script>
// 设定 A4 尺寸为 795 * 1125，印章大小为 159 * 159
const A4_WIDTH = 816;
const A4_HEIGHT = 1156;
const SEAL_SIZE = 159;
const FIX_SEAL_SIZE = 40;
const HALF_SEAL_SIZE = 80;
const HALF_SEAL_SIZE_ARR = [0, 80, 80, 50];
const FIX_SEAL_SIZE_ARR = [0, 40, 110, 80];
import {
  templateDetailReq,
  templateSealListAllReq,
  templateSealCreateReq,
  templateSealDeleteReq,
  postSaveOrUpdate
} from "@/api/company/contract";
import { getToken } from "xqjr-module-auth";
import pdf from "vue-pdf";
import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory.js";
import VueDraggableResizable from "vue-draggable-resizable";
import axios from "axios";
import { isContainByString } from "@/utils/index";
let uuid = 90000000;
export default {
  components: {
    pdf,
    VueDraggableResizable
  },
  inject: ["reload"],
  data() {
    return {
      signType: null,
      isContainByString,
      src: null,
      currentPage: 1,
      pageCount: 0,
      loading: false,
      templateId: null,
      categoryId: null,
      name: "",
      content: "",
      dropList: [],
      oldSealIdList: [],
      a4_width: A4_WIDTH,
      a4_height: A4_HEIGHT,
      seal_size: SEAL_SIZE,
      seal: [],
      sign: [],
      holder: [],
      sealJson: {},
      signJson: {},
      holderJson: {}
    };
  },
  computed: {
    dragList() {
      if (this.signType === "enterprise_only") {
        return ["seal", "holder"];
      } else if (this.signType === "person_only") {
        return ["sign"];
      } else {
        return ["seal", "sign", "holder"];
      }
    }
  },
  watch: {
    pageCount(val) {
      if ((!!val || val === 0) && !this.loading) {
        this.loadTemplateSeals();
      }
    },
    dropList() {
      const seal = this.dropList.filter((e) => e.type === "seal");
      const sign = this.dropList.filter((e) => e.type === "sign");
      const holder = this.dropList.filter((e) => e.type === "holder");
      this.seal = seal;
      this.sign = sign;
      this.holder = holder;
      const sealJson = {};
      const signJson = {};
      const holderJson = {};
      seal.forEach((e) => {
        const numArr = seal.filter((f) => f.page === e.page);
        sealJson[e.page] = numArr.length;
      });
      sign.forEach((e) => {
        const numArr = sign.filter((f) => f.page === e.page);
        signJson[e.page] = numArr.length;
      });
      holder.forEach((e) => {
        const numArr = holder.filter((f) => f.page === e.page);
        holderJson[e.page] = numArr.length;
      });
      this.sealJson = sealJson;
      this.signJson = signJson;
      this.holderJson = holderJson;
    }
  },
  mounted() {
    this.templateId = this.$route.params.id;
    this.loadTemplate();
  },
  methods: {
    pdfError(err) {
      console.log("Error", err);
    },
    loadTemplate() {
      templateDetailReq(this.templateId, this.$route.meta.pageType)
        .then((res) => {
          this.categoryId = res.data.categoryId;
          this.name = res.data.name;
          this.content = res.data.content;
          this.signType = sessionStorage.getItem("cateSignType") || res.data.signType;
          this.$nextTick(() => {
            this.loadTemplatePdf();
          });
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    loadTemplatePdf() {
      axios({
        url: "/contract/api/v1/templates/preview",
        method: "post",
        responseType: "blob",
        headers: {
          token: getToken()
        },
        data: {
          fileName: this.name,
          content: this.content
        }
      })
        .then(async (res) => {
          if (URL && URL.createObjectURL) {
            const urlObj = URL.createObjectURL(new Blob([res.data], { type: "application/pdf" }));
            this.src = pdf.createLoadingTask({ url: urlObj, CMapReaderFactory });
          }
          // this.reload();
          // if (this.src.docId !== "d0") {
          //   this.reload();
          //   return;
          // }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    loadTemplateSeals() {
      this.loading = true;
      templateSealListAllReq(this.templateId, this.$route.meta.pageType)
        .then((res) => {
          this.dropList = res.data.map((item) => ({
            id: item.id,
            page: item.sealPage > this.pageCount ? this.pageCount : item.sealPage,
            x: (item.sealPositionX / 612) * this.a4_width - HALF_SEAL_SIZE_ARR[item.accountType],
            y: this.a4_height - FIX_SEAL_SIZE_ARR[item.accountType] - (item.sealPositionY / 792) * this.a4_height,
            type: this.transType(item.accountType, item.type)
          }));
          this.oldSealIdList = this.dropList.map((item) => item.id);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    transType(aType, type) {
      if (aType === 1) {
        return type === 1 ? "sign" : "sign_date";
      } else if (aType === 2) {
        return type === 1 ? "seal" : "seal_date";
      } else if (aType === 3) {
        return "holder";
      } else {
        return "";
      }
    },
    async createTemplateSeal(data) {
      // const res = await templateSealCreateReq(data);
      const res = await postSaveOrUpdate(data, this.templateId, this.$route.meta.pageType);
      this.$message.success("保存成功");
      this.$router.back();
    },
    async deleteTemplateSeal(ids) {
      const res = await templateSealDeleteReq(ids);
    },
    goback() {
      this.$confirm({
        title: "印章位置设置尚未保存，是否确认离开？",
        okText: "确定",
        cancelText: "取消",
        onOk: () => {
          this.$router.back();
        }
      });
    },
    save() {
      var arr = [];
      for (let i = 0; i < this.dropList.length; i++) {
        const accountType = { seal: 2, seal_date: 2, sign: 1, sign_date: 1, holder: 3 }[this.dropList[i]["type"]];
        arr.push({
          accountType: accountType,
          sealPage: this.dropList[i]["page"],
          sealPositionX: ((this.dropList[i]["x"] + HALF_SEAL_SIZE_ARR[accountType]) / this.a4_width) * 612,
          sealPositionY: ((this.a4_height - FIX_SEAL_SIZE_ARR[accountType] - this.dropList[i]["y"]) / this.a4_height) * 792,
          type: { seal: 1, seal_date: 2, sign: 1, sign_date: 2, holder: 1 }[this.dropList[i]["type"]],
          templateId: this.templateId
        });

        // if (this.oldSealIdList.includes(this.dropList[i]["id"])) {
        //   const idx = this.oldSealIdList.findIndex(item => item === this.dropList[i]["id"]);
        //   this.oldSealIdList.splice(idx, 1);
        // }
      }
      this.createTemplateSeal(arr);
      // if (this.oldSealIdList.length > 0) {
      //   // 删除不存在的印章位置
      //   this.deleteTemplateSeal(this.oldSealIdList);
      // }
      // // this.$router.push('/contract/type')
      // // 修改为跳转合同类型设置-合同模板页面
      // this.$router.push({
      //   path: `/${this.isContainByString("contractAdmin") ? "contractAdmin" : "contract"}/setting`,
      //   query: { id: this.categoryId, current: "2", currentSetting: "1" }
      // });
    },
    onDrag(args, id) {
      const index = this.dropList.findIndex((item) => item.id === id);
      this.dropList[index] = Object.assign(this.dropList[index], {
        x: args[0],
        y: args[1]
      });
    },
    add(type) {
      // if (this.dropList.filter(item => item.type === type).length > 0) {
      //   return;
      // }
      this.dropList.push({
        id: 1 + uuid,
        type: type,
        page: 0 + this.currentPage,
        x: this.dropList.length * 20,
        y: this.dropList.length * 20
      });
      uuid++;
    },
    remove(id) {
      const index = this.dropList.findIndex((item) => item.id === id);
      this.dropList.splice(index, 1);
    },
    pageUp() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    pageDown() {
      if (this.currentPage < this.pageCount) {
        this.currentPage++;
      }
    },
    jump(i) {
      this.currentPage = parseInt(i);
    }
  }
};
</script>
<style lang="scss" scoped>
.ql-editor-content2 {
  padding: 0 !important;
  display: flex;
  justify-content: center;
  .editor-main2 {
    position: static;
    width: 900px;
    margin: 0 auto;
    padding: 16px 0;
    overflow: auto;
  }
  .sealnew-name {
    min-height: 32px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 auto;
    margin-bottom: 12px;
    .left {
      font-size: 16px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.85);
    }
  }
  .editor-config2 {
    position: static;
    width: 400px;
    padding: 20px;
    overflow: auto;
    border-left: 0;
  }
}
.editor-tit {
  margin-top: 16px;
  font-size: 12px;
  color: #d2d2d2;
  span {
    color: var(--primary);
  }
}
.editor-tags {
  width: 180px;
  margin-top: 12px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  .editor-tags-item {
    width: 75px;
    height: 22px;
    background: #f4f4f4;
    border-radius: 2px;
    border: 1px solid #e8e8e8;
    font-size: 12px;
    font-weight: 400;
    color: #595959;
    text-align: center;
    cursor: pointer;
    margin-bottom: 8px;
  }
}
.ql-editor-footer2 {
  position: sticky;
  left: 0;
  bottom: 0;
  z-index: 10;
  background: #fff;
}
</style>
